<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>16.5. getopt — Parser for command line options &mdash; Python v2.6.2 documentation</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '2.6.2',
        COLLAPSE_MODINDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="search" type="application/opensearchdescription+xml"
          title="Search within Python v2.6.2 documentation"
          href="../_static/opensearch.xml"/>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="copyright" title="Copyright" href="../copyright.html" />
    <link rel="top" title="Python v2.6.2 documentation" href="../index.html" />
    <link rel="up" title="16. Generic Operating System Services" href="allos.html" />
    <link rel="next" title="16.6. logging — Logging facility for Python" href="logging.html" />
    <link rel="prev" title="16.4. optparse — More powerful command line option parser" href="optparse.html" />
    <link rel="shortcut icon" type="image/png" href="../_static/py.png" />
 

  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             accesskey="M">modules</a> |</li>
        <li class="right" >
          <a href="logging.html" title="16.6. logging — Logging facility for Python"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="optparse.html" title="16.4. optparse — More powerful command line option parser"
             accesskey="P">previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.6.2 documentation</a> &raquo;</li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="allos.html" accesskey="U">16. Generic Operating System Services</a> &raquo;</li> 
      </ul>
    </div>  

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="module-getopt">
<h1>16.5. <tt class="xref docutils literal"><span class="pre">getopt</span></tt> &#8212; Parser for command line options<a class="headerlink" href="#module-getopt" title="Permalink to this headline">¶</a></h1>
<p>This module helps scripts to parse the command line arguments in <tt class="docutils literal"><span class="pre">sys.argv</span></tt>.
It supports the same conventions as the Unix <tt class="xref docutils literal"><span class="pre">getopt</span></tt> function (including
the special meanings of arguments of the form &#8216;<tt class="docutils literal"><span class="pre">-</span></tt>&#8216; and &#8216;<tt class="docutils literal"><span class="pre">--</span></tt>&#8216;).  Long
options similar to those supported by GNU software may be used as well via an
optional third argument.</p>
<p>A more convenient, flexible, and powerful alternative is the
<a title="More convenient, flexible, and powerful command-line parsing library." class="reference external" href="optparse.html#module-optparse"><tt class="xref docutils literal"><span class="pre">optparse</span></tt></a> module.</p>
<p>This module provides two functions and an
exception:</p>
<dl class="function">
<dt id="getopt.getopt">
<tt class="descclassname">getopt.</tt><tt class="descname">getopt</tt><big>(</big><em>args</em>, <em>options</em><span class="optional">[</span>, <em>long_options</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#getopt.getopt" title="Permalink to this definition">¶</a></dt>
<dd><p>Parses command line options and parameter list.  <em>args</em> is the argument list to
be parsed, without the leading reference to the running program. Typically, this
means <tt class="docutils literal"><span class="pre">sys.argv[1:]</span></tt>. <em>options</em> is the string of option letters that the
script wants to recognize, with options that require an argument followed by a
colon (<tt class="docutils literal"><span class="pre">':'</span></tt>; i.e., the same format that Unix <tt class="xref docutils literal"><span class="pre">getopt</span></tt> uses).</p>
<div class="admonition note">
<p class="first admonition-title">Note</p>
<p class="last">Unlike GNU <tt class="xref docutils literal"><span class="pre">getopt</span></tt>, after a non-option argument, all further arguments
are considered also non-options. This is similar to the way non-GNU Unix systems
work.</p>
</div>
<p><em>long_options</em>, if specified, must be a list of strings with the names of the
long options which should be supported.  The leading <tt class="docutils literal"><span class="pre">'-</span></tt><tt class="docutils literal"><span class="pre">-'</span></tt> characters
should not be included in the option name.  Long options which require an
argument should be followed by an equal sign (<tt class="docutils literal"><span class="pre">'='</span></tt>).  To accept only long
options, <em>options</em> should be an empty string.  Long options on the command line
can be recognized so long as they provide a prefix of the option name that
matches exactly one of the accepted options.  For example, if <em>long_options</em> is
<tt class="docutils literal"><span class="pre">['foo',</span> <span class="pre">'frob']</span></tt>, the option <em class="xref">--fo</em> will match as <em class="xref">--foo</em>,
but <em class="xref">--f</em> will not match uniquely, so <a title="getopt.GetoptError" class="reference internal" href="#getopt.GetoptError"><tt class="xref docutils literal"><span class="pre">GetoptError</span></tt></a> will be raised.</p>
<p>The return value consists of two elements: the first is a list of <tt class="docutils literal"><span class="pre">(option,</span>
<span class="pre">value)</span></tt> pairs; the second is the list of program arguments left after the
option list was stripped (this is a trailing slice of <em>args</em>).  Each
option-and-value pair returned has the option as its first element, prefixed
with a hyphen for short options (e.g., <tt class="docutils literal"><span class="pre">'-x'</span></tt>) or two hyphens for long
options (e.g., <tt class="docutils literal"><span class="pre">'-</span></tt><tt class="docutils literal"><span class="pre">-long-option'</span></tt>), and the option argument as its
second element, or an empty string if the option has no argument.  The
options occur in the list in the same order in which they were found, thus
allowing multiple occurrences.  Long and short options may be mixed.</p>
</dd></dl>

<dl class="function">
<dt id="getopt.gnu_getopt">
<tt class="descclassname">getopt.</tt><tt class="descname">gnu_getopt</tt><big>(</big><em>args</em>, <em>options</em><span class="optional">[</span>, <em>long_options</em><span class="optional">]</span><big>)</big><a class="headerlink" href="#getopt.gnu_getopt" title="Permalink to this definition">¶</a></dt>
<dd><p>This function works like <a title="getopt.getopt" class="reference internal" href="#getopt.getopt"><tt class="xref docutils literal"><span class="pre">getopt()</span></tt></a>, except that GNU style scanning mode is
used by default. This means that option and non-option arguments may be
intermixed. The <a title="getopt.getopt" class="reference internal" href="#getopt.getopt"><tt class="xref docutils literal"><span class="pre">getopt()</span></tt></a> function stops processing options as soon as a
non-option argument is encountered.</p>
<p>If the first character of the option string is &#8216;+&#8217;, or if the environment
variable <span class="target" id="index-336"></span><strong class="xref">POSIXLY_CORRECT</strong> is set, then option processing stops as
soon as a non-option argument is encountered.</p>
<p>
<span class="versionmodified">New in version 2.3.</span></p>
</dd></dl>

<dl class="exception">
<dt id="getopt.GetoptError">
<em class="property">
exception </em><tt class="descclassname">getopt.</tt><tt class="descname">GetoptError</tt><a class="headerlink" href="#getopt.GetoptError" title="Permalink to this definition">¶</a></dt>
<dd><p>This is raised when an unrecognized option is found in the argument list or when
an option requiring an argument is given none. The argument to the exception is
a string indicating the cause of the error.  For long options, an argument given
to an option which does not require one will also cause this exception to be
raised.  The attributes <tt class="xref docutils literal"><span class="pre">msg</span></tt> and <tt class="xref docutils literal"><span class="pre">opt</span></tt> give the error message and
related option; if there is no specific option to which the exception relates,
<tt class="xref docutils literal"><span class="pre">opt</span></tt> is an empty string.</p>
<p>
<span class="versionmodified">Changed in version 1.6: </span>Introduced <a title="getopt.GetoptError" class="reference internal" href="#getopt.GetoptError"><tt class="xref docutils literal"><span class="pre">GetoptError</span></tt></a> as a synonym for <a title="getopt.error" class="reference internal" href="#getopt.error"><tt class="xref docutils literal"><span class="pre">error</span></tt></a>.</p>
</dd></dl>

<dl class="exception">
<dt id="getopt.error">
<em class="property">
exception </em><tt class="descclassname">getopt.</tt><tt class="descname">error</tt><a class="headerlink" href="#getopt.error" title="Permalink to this definition">¶</a></dt>
<dd>Alias for <a title="getopt.GetoptError" class="reference internal" href="#getopt.GetoptError"><tt class="xref docutils literal"><span class="pre">GetoptError</span></tt></a>; for backward compatibility.</dd></dl>

<p>An example using only Unix style options:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">getopt</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="s">&#39;-a -b -cfoo -d bar a1 a2&#39;</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span>
<span class="go">[&#39;-a&#39;, &#39;-b&#39;, &#39;-cfoo&#39;, &#39;-d&#39;, &#39;bar&#39;, &#39;a1&#39;, &#39;a2&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">optlist</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="n">getopt</span><span class="o">.</span><span class="n">getopt</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&#39;abc:d:&#39;</span><span class="p">)</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">optlist</span>
<span class="go">[(&#39;-a&#39;, &#39;&#39;), (&#39;-b&#39;, &#39;&#39;), (&#39;-c&#39;, &#39;foo&#39;), (&#39;-d&#39;, &#39;bar&#39;)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span>
<span class="go">[&#39;a1&#39;, &#39;a2&#39;]</span>
</pre></div>
</div>
<p>Using long option names is equally easy:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="gp">&gt;&gt;&gt; </span><span class="n">s</span> <span class="o">=</span> <span class="s">&#39;--condition=foo --testing --output-file abc.def -x a1 a2&#39;</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span> <span class="o">=</span> <span class="n">s</span><span class="o">.</span><span class="n">split</span><span class="p">()</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span>
<span class="go">[&#39;--condition=foo&#39;, &#39;--testing&#39;, &#39;--output-file&#39;, &#39;abc.def&#39;, &#39;-x&#39;, &#39;a1&#39;, &#39;a2&#39;]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">optlist</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="n">getopt</span><span class="o">.</span><span class="n">getopt</span><span class="p">(</span><span class="n">args</span><span class="p">,</span> <span class="s">&#39;x&#39;</span><span class="p">,</span> <span class="p">[</span>
<span class="gp">... </span>    <span class="s">&#39;condition=&#39;</span><span class="p">,</span> <span class="s">&#39;output-file=&#39;</span><span class="p">,</span> <span class="s">&#39;testing&#39;</span><span class="p">])</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">optlist</span>
<span class="go">[(&#39;--condition&#39;, &#39;foo&#39;), (&#39;--testing&#39;, &#39;&#39;), (&#39;--output-file&#39;, &#39;abc.def&#39;), (&#39;-x&#39;, &#39;&#39;)]</span>
<span class="gp">&gt;&gt;&gt; </span><span class="n">args</span>
<span class="go">[&#39;a1&#39;, &#39;a2&#39;]</span>
</pre></div>
</div>
<p>In a script, typical usage is something like this:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">getopt</span><span class="o">,</span> <span class="nn">sys</span>

<span class="k">def</span> <span class="nf">main</span><span class="p">():</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">opts</span><span class="p">,</span> <span class="n">args</span> <span class="o">=</span> <span class="n">getopt</span><span class="o">.</span><span class="n">getopt</span><span class="p">(</span><span class="n">sys</span><span class="o">.</span><span class="n">argv</span><span class="p">[</span><span class="mf">1</span><span class="p">:],</span> <span class="s">&quot;ho:v&quot;</span><span class="p">,</span> <span class="p">[</span><span class="s">&quot;help&quot;</span><span class="p">,</span> <span class="s">&quot;output=&quot;</span><span class="p">])</span>
    <span class="k">except</span> <span class="n">getopt</span><span class="o">.</span><span class="n">GetoptError</span><span class="p">,</span> <span class="n">err</span><span class="p">:</span>
        <span class="c"># print help information and exit:</span>
        <span class="k">print</span> <span class="nb">str</span><span class="p">(</span><span class="n">err</span><span class="p">)</span> <span class="c"># will print something like &quot;option -a not recognized&quot;</span>
        <span class="n">usage</span><span class="p">()</span>
        <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">(</span><span class="mf">2</span><span class="p">)</span>
    <span class="n">output</span> <span class="o">=</span> <span class="bp">None</span>
    <span class="n">verbose</span> <span class="o">=</span> <span class="bp">False</span>
    <span class="k">for</span> <span class="n">o</span><span class="p">,</span> <span class="n">a</span> <span class="ow">in</span> <span class="n">opts</span><span class="p">:</span>
        <span class="k">if</span> <span class="n">o</span> <span class="o">==</span> <span class="s">&quot;-v&quot;</span><span class="p">:</span>
            <span class="n">verbose</span> <span class="o">=</span> <span class="bp">True</span>
        <span class="k">elif</span> <span class="n">o</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&quot;-h&quot;</span><span class="p">,</span> <span class="s">&quot;--help&quot;</span><span class="p">):</span>
            <span class="n">usage</span><span class="p">()</span>
            <span class="n">sys</span><span class="o">.</span><span class="n">exit</span><span class="p">()</span>
        <span class="k">elif</span> <span class="n">o</span> <span class="ow">in</span> <span class="p">(</span><span class="s">&quot;-o&quot;</span><span class="p">,</span> <span class="s">&quot;--output&quot;</span><span class="p">):</span>
            <span class="n">output</span> <span class="o">=</span> <span class="n">a</span>
        <span class="k">else</span><span class="p">:</span>
            <span class="k">assert</span> <span class="bp">False</span><span class="p">,</span> <span class="s">&quot;unhandled option&quot;</span>
    <span class="c"># ...</span>

<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s">&quot;__main__&quot;</span><span class="p">:</span>
    <span class="n">main</span><span class="p">()</span>
</pre></div>
</div>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt>Module <a title="More convenient, flexible, and powerful command-line parsing library." class="reference external" href="optparse.html#module-optparse"><tt class="xref docutils literal"><span class="pre">optparse</span></tt></a></dt>
<dd>More object-oriented command line option parsing.</dd>
</dl>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
            <h4>Previous topic</h4>
            <p class="topless"><a href="optparse.html"
                                  title="previous chapter">16.4. <tt class="docutils literal"><span class="pre">optparse</span></tt> &#8212; More powerful command line option parser</a></p>
            <h4>Next topic</h4>
            <p class="topless"><a href="logging.html"
                                  title="next chapter">16.6. <tt class="docutils literal"><span class="pre">logging</span></tt> &#8212; Logging facility for Python</a></p>
            <h3>This Page</h3>
            <ul class="this-page-menu">
              <li><a href="../_sources/library/getopt.txt"
                     rel="nofollow">Show Source</a></li>
            </ul>
          <div id="searchbox" style="display: none">
            <h3>Quick search</h3>
              <form class="search" action="../search.html" method="get">
                <input type="text" name="q" size="18" />
                <input type="submit" value="Go" />
                <input type="hidden" name="check_keywords" value="yes" />
                <input type="hidden" name="area" value="default" />
              </form>
              <p class="searchtip" style="font-size: 90%">
              Enter search terms or a module, class or function name.
              </p>
          </div>
          <script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../modindex.html" title="Global Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="logging.html" title="16.6. logging — Logging facility for Python"
             >next</a> |</li>
        <li class="right" >
          <a href="optparse.html" title="16.4. optparse — More powerful command line option parser"
             >previous</a> |</li>
        <li><img src="../_static/py.png" alt=""
                 style="vertical-align: middle; margin-top: -1px"/></li>
        <li><a href="../index.html">Python v2.6.2 documentation</a> &raquo;</li>

          <li><a href="index.html" >The Python Standard Library</a> &raquo;</li>
          <li><a href="allos.html" >16. Generic Operating System Services</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
      &copy; <a href="../copyright.html">Copyright</a> 1990-2009, Python Software Foundation.
      Last updated on Apr 15, 2009.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 0.6.1.
    </div>
  </body>
</html>